<template>
  <p-drawer
    placement="right"
    :closable="false"
    width="calc(100vw - 200px)"
    :visible="visible"
    :mask-closable="false"
    :destroy-on-close="true"
    @close="onClose"
  >
    <div style="position: relative">
      <TaskTitle :icon-name="iconName" :title-name="titleName" :color="color" />
      <p-button
        v-if="isEdit || !addState"
        class="commonbutton edit"
        type="primary"
        @click="edit"
      >
        编辑
      </p-button>
    </div>
    <div class="g-drawer-list-container" style="overflow-x: hidden">
      <TitleSecondary title="基本信息" />
      <AddContractForm
        ref="form"
        :form="form"
        :is-foot="isFoot"
        :add-state="addState"
        :delete-file-id.sync="deleteFileId"
      />
    </div>
    <ButtonGroup
      class="g-drawer-footer"
      :options="footerButtons"
      @click="handleButtonClick"
    />
  </p-drawer>
</template>

<script>
import monent from 'moment';
import { postDeleteFile } from '@/api/order.js';
import AddContractForm from './AddContractForm.vue';
import { postAddContract } from '@/api/contract.js';
import { getCurrentUser } from '@/api/public.js';
import router from '@/router';

const defaultForm = {
  id: '',
  contractNo: '',
  customerCode: '',
  contractName: '',
  contractType: '',
  customerName: '',
  opportunityNo: '',
  contractStatus: '',
  salesContractNo: '',
  opportunityName: '',
  remark: '',
  createUserName: '',
  updateTime: '',
  updateUserName: '',
  createTime: '',
  updateDepartment: '',
  createDepartment: '',
  attachmentList: [],
  logList: [],
};
export default {
  components: {
    AddContractForm,
  },
  // mixins: [DrawerMixin],
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    addState: {
      type: Boolean,
      default: false,
    },
    detail: {
      type: Object,
      default: () => ({}),
    },
    isFoot: {
      type: Boolean,
      default: false,
    },
    titleInfo: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      form: {
        ...defaultForm,
      },
      titleName: '合同详情',
      color: 'green',
      iconName: 'Det',
      planIdNew: undefined,
      saleList: [],
      isEdit: false,
      currentUser: '',
      currentUserOrg: '',
      isSave: false,
      deleteFileId: [],
    };
  },

  computed: {
    footerButtons() {
      const buttons = this.addState
        ? [
            {
              key: 'save',
              type: 'primary',
              label: '保存',
              auth: true,
            },
            {
              key: 'close',
              label: '返回',
            },
          ]
        : [
            {
              key: 'close',
              label: '返回',
            },
          ];
      return buttons;
    },
  },
  watch: {
    visible: {
      handler(val) {
        this.getCurrentInfo();
        if (!val) return;
        if (this.detail.type === 'routerAdd') {
          this.form.customerName = this.detail.customerName;
          this.form.customerCode = this.detail.customerCode;
        }
        if (!this.addState) {
          const plan = this.detail || {};
          this.isEdit = true;
          this.form = {
            id: plan.id || '',
            contractNo: plan.contractNo || '',
            // salesGroupCode: plan.createUserGroup,
            // salesGroupCode:plan.salesGroupCode||'',
            contractType: plan.contractType || '',
            contractName: plan.contractName || '',
            customerName: plan.customerName || '',
            customerCode: plan.customerCode || '',
            opportunityNo: plan.opportunityNo || '',
            contractStatus: plan.contractStatus || '',
            salesContractNo: plan.salesContractNo || '',
            opportunityName: plan.opportunityName || '',
            createUserName: plan.createUserName || '',
            remark: plan.remark || '',
            updateTime: plan.updateTime || '',
            updateUserName: plan.updateUserName || '',
            createTime: plan.createTime || '',
            updateDepartment: plan.updateDepartment || '',
            createDepartment: plan.createDepartment || '',
            attachmentList: plan.attachmentList || [],
            logList: plan.logList || [],
          };
        }
      },
    },
    // addState: {
    //   handler(val) {
    //     console.log('val: ', val);
    //     if (val) {
    //       this.titleName = '新增订单';
    //       this.color = 'red';
    //       this.iconName = 'New';
    //     }
    //   },
    //   immediate: true,
    // },
    titleInfo: {
      handler(val) {
        this.titleName = val.titleName;
        this.color = val.color;
        this.iconName = val.iconName;
      },
      deep: true,
    },
  },
  created() {
    this.loadRouterInfo();
  },
  methods: {
    loadRouterInfo() {
      const routerInfo = this.$route.query;
      if (JSON.stringify(routerInfo) !== '{}') {
        this.form.opportunityNo = routerInfo.opportunityNo;
        this.form.opportunityName = routerInfo.opportunityName;
        this.form.customerName = routerInfo.customerShortName;
        this.form.customerCode = routerInfo.customerCode;
      }
    },
    async edit() {
      this.titleName = '编辑合同';
      this.color = 'blue';
      this.iconName = 'Edit';
      this.isSave = true;
      this.$emit('update:addState', true);
      this.isEdit = false;

      // const currentUserOrg = result?.data?.data?.orgPosDtos[0] || {};
      // console.log('currentUserOrg: ', currentUserOrg);
      // const orgs = currentUserOrg?.codePath.split('/');
      // const ind = orgs.findIndex((item) => item === 'ltcsmsizebu');
      // this.currentUserOrg = orgs[ind + 1];
    },
    clearList() {
      this.saleList = [];
    },
    async getCurrentInfo() {
      const result = await getCurrentUser();
      this.currentUser = result?.data?.data?.name || '';
      this.currentUserOrg = result?.data?.data?.departmentName || '';
      this.currentUserOrg = this.removalSame(this.currentUserOrg);
    },
    removalSame(obj) {
      obj = obj.replace(/\s*/g, '');
      const array = obj.split(',');
      console.log('array: ', array);
      const departmentName = [...new Set(array)].join(',');
      return departmentName;
    },
    onClose() {
      this.titleName = '合同详情';
      this.color = 'green';
      this.iconName = 'Det';
      this.form = { ...defaultForm };
      this.isEdit = false;
      this.deleteFileId = [];
      this.$emit('update:isFoot', false);
      this.$emit('update:visible', false);
      this.$emit('fresh');
    },

    async saveCallback() {
      const valid = await this.$refs.form.validate();
      if (!valid) return new Promise(() => {});
      if (this.deleteFileId.length) {
        const result = await postDeleteFile(this.deleteFileId);
        this.deleteFileId = [];
      }
      const formInfo = JSON.parse(JSON.stringify(this.$refs.form.form));
      if (!this.$refs.form.list.length) {
        formInfo.attachmentList = [];
      }
      formInfo.attachmentList = this.$refs.form.fileList;
      formInfo.updateDepartment = this.currentUserOrg;
      formInfo.updateUserName = this.currentUserOrg || '';
      if (this.isSave) {
        const result = await postAddContract(formInfo);
        if (result.data.code === 0) {
          this.$message.success('保存成功！');
          this.closeCallback();
        }
      } else {
        formInfo.createDepartment = this.currentUserOrg || '';
        const result = await postAddContract(formInfo);
        if (result.data.code === 0) {
          this.$message.success('保存成功！');
          this.closeCallback();
          this.isSave = false;
        }
      }

      // const serialNumber = result?.data?.data?.serialNumber;
      // this.planIdNew = result?.data?.data?.id;
      // this.$refs.form.setForm(serialNumber);
    },
    closeCallback() {
      this.onClose();
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      this[fn] && this[fn]();
    },
  },
};
</script>
<style lang="less" scoped>
.edit {
  position: absolute;
  top: 10px;
  right: 30px;
}
</style>


